<?php

namespace app\index\controller;

use classes\RedisClass;
use think\Controller;
use think\Db;
use think\facade\Cache;
use classes\TokenBucket;
use Jenssegers\Agent\Agent;
use think\Queue;

class Index extends Controller
{

    public function index()
    {
//        $this->redirect('@admin/login');
    }


    public function smsto()
    {

        $list = Db::name('tp_vote_item')->where('status', -1)->select();
        foreach ($list as $one) {
            $checkinfo = $one['checkinfo'];
            $msg = "【郎酒股份】您报名参与“郎酒醉美品牌形象店”活动的报名信息审核未通过(原因：{$checkinfo})，请重新提交相关信息！";
            send_sms_to_mobile($one['phone'], $msg);
        }
        die('ok');
    }

    public function test_ip()
    {

        $Ip2Region = new \Ip2Region();
        $result = $Ip2Region->btreeSearch('117.136.72.101');
        $result = explode('|', $result['region']);
//            $area = str_replace(['内网IP', '中国', '0', '|'], '', $result['region']);
        print_dump($result);
        $result = getClientMobileBrand('Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 NetType/WIFI MicroMessenger/7.0.20.1781(0x6700143B) WindowsWechat(0x63030532)');

//        $result = getIpInfo('223.104.63.18');
        print_dump($result);
    }

    public function test_limit()
    {


        $curnum = intval(Cache::store('redis')->handler()->LLEN('mycontainer'));
        // 重设令牌桶，填满令牌
//        TokenBucket::reset();
//        print_dump(TokenBucket::get());
        print_dump($curnum);
        // 循环获取令牌，令牌桶内只有5个令牌，因此最后3次获取失败
        for ($i = 0; $i < 8; $i++) {
            var_dump(TokenBucket::get());
        }

        // 加入20个令牌，最大令牌为10，因此只能加入10个
//        $add_num = TokenBucket::add(20);

//        var_dump($add_num);

        // 循环获取令牌，令牌桶内只有10个令牌，因此最后1次获取失败
        for ($i = 0; $i < 11; $i++) {
            var_dump(TokenBucket::get());
        }

    }

    /**
     * 动画
     * @return bool|mixed
     */
    public function animation()
    {

        //分享朋友圈
//        $current_url = $this->request->url(true);
        $current_url = 'http://xljvote.zoudingyong.com/';
        try {
            $wx_config = [
                'appid' => sysconf('wechat_appid'),
                'appsecret' => sysconf('wechat_appsecret'),
            ];
            $wechat = \WeChat\Script::instance($wx_config);
            $signPackage = $wechat->getJsSign($current_url);
        } catch (\Exception $e) {
            $signPackage = [
                'appId' => sysconf('wechat_appid'),
                'timestamp' => '',
                'nonceStr' => '',
                'signature' => '',
                'current_url' => $current_url,
            ];
        };

        echo "var signPackage=";
        die(json_encode($signPackage));// 返回微信分享所需参数
        return json(['result' => $signPackage]);


    }


    public function ticket2()
    {

//        $config = RedisClass::get_vote_config_info();
//        Cache::store('redis')->handler()->hset('vote:config', 'total_vcount', $config['total_vcount'] + 300); //总票数+
    }

    public function test()
    {

        //项目
        $itemList = Db::name('tp_vote_item')
            ->field('id,videourl,small_pic')
            ->whereLike('videourl', "%jtyhvideo%")
            ->select();
        if (!empty($itemList)) {
            foreach ($itemList as $one) {

                //视频截帧（cos配置工作流）
                $url_arr = explode('http://jtyhvideo.zoudingyong.com', $one['videourl']);
                $url_arr = explode('.', $url_arr[1]);
                $small_pic = 'http://jtyhvideo.zoudingyong.com' . $url_arr[0] . '_0.jpg';

                Db::name('tp_vote_item')->where('id', $one['id'])->update([
                    'small_pic' => $small_pic,
                ]);
                RedisClass::del_item_info($one['id']);

            }
            echo 'ok';
        } else {
            echo 'fail';
        }

//        $url_arr = explode('http://jtyhvideo.zoudingyong.com', 'http://jtyhvideo.zoudingyong.com/static/xlj_video/002023051321052514511041104031.mp4');
//        $url_arr = explode('.', $url_arr[1]);
//
//        $url_arr = 'http://jtyhvideo.zoudingyong.com' . $url_arr[0] . '_0.jpg';
//        print_dump($url_arr);
//        $data = explode(',', '熊连英,刘敏,戈仕桃,熊菊英,裴昌君,彭光锐,熊小红,唐秀华,吴敏,黄炳英,黄小琴,黄成莲,陈俊,石顺玲,林玉青,吴桃英,李良芳,邱灯红,刘丽,陈晋花,曾冠一,温海玲,朱雨珍,刘星敏,叶超宁,熊美玉,何建英,濮兰香,陈景春,聂忠玲,廖彦琴,陈永华,张萍,左仁巨,钟群英,王章贤,何红云,唐慈鸿,李贵英,胡小梅,何冬梅,江秀媄,郑礼秀,刘辛霞,蔡亚梅,廖君华,祁加红,陈婷,何叶倩,马丽霞,唐小琼,朱盛淑,张利敏,田志兰,陈秀容,韩守红,马兴芬,张双,刘亚玲,李兴丽,张庭英,唐瑕,王敏,熊雪玲,罗玲,王晓梅,陈英,齐佳,林晶,周筱兰,王金双,向碧兰,李红英,胡华,张玲,陈芬,庄芬芳,蔡玉平,肖春花,陈凤琼,蒋志连,丘宝平,罗金艳,蒋艳琼,余娇,林燕丽,梁海妮,黄凤娇,李伟华,邱嘉琪,陈丽霞,蔡燕英,刘亨莉,何小任,农梅湖,屈宜翠,丘素花,刘得保,赖小华,温海燕,陈春凤,李红,陈飞容,吴雪燕,李志媚,彭红香,汪喜娣,周艳兰,莫四干,陈佩霞,邝淑清,赵荣,卢业,李小燕,王秋红,胡正梅,唐义花,严长凤,宋丽霞,金丽萍,胡春丽,琚晓,汪秀真,秦路路,孟翠萍,沈小花,沈丽,曾文娣,闫素侠,王新清,韩标,范海英,王芬,刘建香,苏淑莲,张焕男,孟莹,贾东平,王秀红,曹维敏,高美红,韩燕丽,赵建军,曹淑娟,孙士英,付春艳,于腊梅,宋亚平,戈英,祝千惠,龚小春,孙淑聪,何爱军,杨美兰,朱仲华,韩英,鲁荣新,贺双凤,姜朝霞,黄相坤,容美香,林美珠,刘丽红,宋瑞霞,林淑萍,谷春艳,郑林润,陈凤娇,谢爱莲,潘林,李秀波,孟显宇,覃清莲,吴晓静,陈海亚,彭春梅,颜秋芳,袁爱杰,陈淑娟,沈艳方,向国林,李颖,冯蕾蕾,段付秀,夏守梅,王红梅,张金娥,李媛媛,刘年,李梅,程玉艳,付秀珍,谭芳,张杏杏,吴彩花,刘芳,钱亮,谢泽俠,张静义,张小雯');
//        //删除未进入复赛的选手  1
//        $itemList = Db::name('tp_vote_item')
//            ->whereNotIn('item', $data)
//            ->delete();
//        if ($itemList) {
//            echo 'ok';
//        } else {
//            echo 'fail';
//        }


        //更新赛区  2
//        $itemList = Db::name('tp_vote_item')
//            ->where('cate_id<>30 ')
//            ->setField('cate_id',2);
//        if ($itemList) {
//            echo 'ok';
//        } else {
//            echo 'fail';
//        }

        //更新赛区 3
//        $itemList = Db::name('tp_vote_item')
//            ->where('cate_id=30 ')
//            ->setField('cate_id', 1);
//        if ($itemList) {
//            echo 'ok';
//        } else {
//            echo 'fail';
//        }


        //项目
//        $itemList = Db::name('tp_vote_item')
//            ->alias('a')
//            ->field('a.id,a.wechat_id')
//            ->select();
//        if (!empty($itemList)) {
//            foreach ($itemList as $one) {
//                RedisClass::set_redis_item_by_openid($one['wechat_id']);
//            }
//            echo 'ok';
//        } else {
//            echo 'fail';
//        }

//        $result = \service\FileService::download_cos2('http://jtyhvideo.zoudingyong.com/static/upload/6635899ecfe5024a/d7ecacb6812720bf.jpeg');
//        print_dump($result);
//
//        //项目
//        $itemList = Db::name('tp_vote_item')
//            ->field('id,is_down,startpicurl,small_pic')
//            ->where('is_down', 1)
////            ->limit(10)
//            ->select();
//        if (!empty($itemList)) {
//            foreach ($itemList as $one) {
//
//                Db::name('tp_vote_item')->where('id', $one['id'])->update([
//                    'startpicurl' => $one['small_pic'],
//                ]);
//                RedisClass::del_item_info($one['id']);
//
//            }
//            echo 'ok';
//        } else {
//            echo 'fail';
//        }

        //项目
//        $itemList = Db::name('tp_vote_item')
//            ->field('id,is_down,startpicurl,small_pic')
//            ->where('is_down', 1)
//            ->where('id < 1285')
//            ->limit(10)
//            ->select();
////        print_dump($itemList);
//        if (!empty($itemList)) {
//            foreach ($itemList as $one) {
//
//                $result = \service\FileService::download_cos2($one['startpicurl']);
//
//                Db::name('tp_vote_item')->where('id', $one['id'])->update([
//                    'small_pic' => $result['url'],
//                    'is_down' => 1,
//                ]);
//            }
//            echo 'ok';
//        } else {
//            echo 'fail';
//        }


        //项目
//        $itemList = Db::name('tp_vote_item')
//            ->alias('a')
//            ->field('a.id,a.phone')
//            ->select();
//        if (!empty($itemList)) {
//            foreach ($itemList as $one) {
//                Db::name('tp_sales')->where('mobile', $one['phone'])->setField('is_reg', 1);
//            }
//        }
//        echo 'ok';

//        $id = 1074;
//        RedisClass::del_item_info($id);
//        Cache::store('redis')->handler()->zRem('vote:item_ids', $id); //全部项目
//        Cache::store('redis')->handler()->zRem('vote:item_ids5', $id);//分类项目
//        Cache::store('redis')->handler()->zRem('vote:score:ids', $id);//全部排名
//        Cache::store('redis')->handler()->zRem('vote:score:ids5', $id); //分类排名
//        echo 'ok';
//        Cache::store('redis')->rm('view_count');
//        $view_count = Cache::store('redis')->inc('view_count',37924); //总浏览数


//        Cache::store('redis')->rm('total_vcount');
//        $view_count = Cache::store('redis')->inc('total_vcount');

//        $total_vcount = Cache::store('redis')->inc('total_vcount'); //总投票量

//                $data = getRedGift(234, 200);
//
//        foreach ($data['MoneySum'] as $key=>$one){
//            Db::name('tp_redpacket')->insert([
//                'money' => $one,
//            ]);
//        }
//
//        print_dump($data);

//        $redpacketId = Cache::store('redis')->handler()->LPOP('redpacket:left');
//        if ($redpacketId) {
//            print_dump($this->getRedPaceketInfo($redpacketId, 1));
//        } else {
//            return '无数据';
//        }

//        $couponId = Cache::store('redis')->handler()->LPOP('jj_coupon:left');
//        if ($couponId) {
//            print_dump($this->updateCouponInfo($couponId, 1));
//        } else {
//            return '无数据';
//        }
    }

    public function ticket()
    {


        $wecha_id = 'o6rBgxER1najTK-KGVmQSa9iPZig';
        $today = date("Y-m-d");
        $tomorrow = strtotime(date("Y-m-d", strtotime("+1 day")));
//        $itemId = input('id');
        $itemId = '1177';

        if (!$wecha_id) {
            return json(['code' => 110, 'message' => '请授权访问(code:110)!']);
        }

        if (!$itemId) {
            return json(['code' => 110, 'message' => '操作异常,请刷新重试(code:110)']);
        }

        $config = RedisClass::get_vote_config_info();
        $item = RedisClass::get_redis_item_info($itemId);

//        $is_captcha = Cache::get('captcha_' . $wecha_id);
//        if ($config['captcha'] && !$is_captcha) {
//            return json(['code' => 110, 'message' => '操作异常,请刷新当前页面！']);
//        }

        //停机检修,暂停
        if ($config['switch']) {
            return json(['code' => 113, 'message' => '网络异常,请稍后再试(113)']);
        }

        if ($config['statdate'] > time()) {
            return json(['code' => 103, 'message' => '点赞未开始']);

        }
        if ($config['enddate'] < time()) {
            return json(['code' => 104, 'message' => '点赞已结束']);
        }

        if (!$item) {
            return json(['code' => 110, 'message' => '数据异常,请刷新重试(code:110)']);
        }

        if ($item['status'] != 1) {
            return json(['code' => 107, 'message' => '此选手无法点赞，可能出于审核中或已被屏蔽！']);
        }

        //开启锁定
        if ($config['lock_status']) {
            $min_result = RedisClass::getTimeVoteCount('vote:lock:item_id:' . $itemId, $config['lock_vote'], $config['lock_min'] * 60); //分钟锁定
            $hour_result = RedisClass::getTimeVoteCount('vote:lock_hour:item_id:' . $itemId, $config['lock_hour_vote'], $config['lock_hour'] * 60 * 60); //小时锁定
            if (!$min_result || !$hour_result) {
                Cache::store('redis')->handler()->hMset('vote:item_id:' . $itemId, ['status' => 2]);
                Db::name('tp_vote_item')->where('id', $itemId)->setField('status', 2);
                return json(['code' => 107, 'message' => $config['lock_msg']]);
            }
        }

        //开启警告
        if ($config['warn_status']) {
            $warn_result = RedisClass::getTimeVoteCount('vote:warn:item_id:' . $itemId, $config['warn_vote'], $config['warn_min'] * 60);
            if (!$warn_result) {
                return json(['code' => 115, 'message' => $config['warn_msg']]);
            }
        }

        //开启时间限制
        if ($config['limit_time_status']) {
            $current_time = date("H:i", time());
            $start = $config['limitdate'];
            $end = $config['limitenddate'];
            if (strtotime($current_time) < strtotime($start) || strtotime($current_time) > strtotime($end)) {
                return json(['code' => 114, 'message' => '当前时间不可点赞!']);
            }
        }

        //开启IP限制
        if ($config['limit_ip_status']) {
            if (!RedisClass::getIpVoteCount($config['limit_vote_ip'])) {
                return json(['code' => 105, 'message' => '当前IP点赞次数过多已被限制!']);
            }
        }

        //开启区域限制
        if ($config['limit_area_status'] > 0) {
            $url = "http://ip.taobao.com/outGetIpInfo?accessKey=alibaba-inc&ip=" . $this->request->ip();
            $result = json_decode(api_notice_increment($url));
            if ($config['limit_area_status'] == 1) {
                $province = $result->data->region;
                if (strpos($config['limit_province'], $province) === false) {
                    return json(['code' => 112, 'message' => '点赞省份限制(112)!']);
                }
            }
            if ($config['limit_area_status'] == 2) {
                $city = $result->data->city;
                if (strpos($config['limit_city'], $city) === false) {
                    return json(['code' => 112, 'message' => '点赞城市限制(112)!']);
                }
            }
        }

        $isHaveTicket = Cache::store('redis')->handler()->LLEN('record:wecha_id:' . $wecha_id . ':time:' . $today);//已点赞数


        if ($wecha_id) {
//            if ($isHaveTicket >= $config['day_vote_count']) {
//                return json(['code' => 106, 'message' => "今天您已经点赞{$config['day_vote_count']}次,明天再来!"]);
//            } else {
            //点赞成功
            $result = Cache::store('redis')->handler()->LPUSH('record:wecha_id:' . $wecha_id . ':time:' . $today, 1); //队列
            Cache::store('redis')->handler()->expireat('record:wecha_id:' . $wecha_id . ':time:' . $today, $tomorrow);//设置过期时间

            //开启ip点赞限制
            if ($config['limit_ip_status']) {
                Cache::store('redis')->handler()->LPUSH('limit:vote:ip:' . $this->request->ip(), 1); //队列
                Cache::store('redis')->handler()->expire('limit:vote:ip:' . $this->request->ip(), 60 * 60 * 6);//设置过期时间
            }

            if ($result) {

                Cache::store('redis')->inc('total_vcount'); //总票数增加
                Cache::store('redis')->handler()->ZINCRBY('vote:score:ids', 1, $itemId);// 项目票数增加  全部排行榜
                Cache::store('redis')->handler()->ZINCRBY('vote:score:ids' . $item['cate_id'], 1, $itemId);// 项目票数增加  分类排行榜

                $record['item_id'] = $itemId;
                $record['wecha_id'] = $wecha_id;
                $record['touch_time'] = time();
                $record['touched'] = 1;
                $record['ip'] = $this->request->ip();
                $record['agent'] = getUA();

                //开启数据延迟写入
                if ($config['delay_status']) {
                    Queue::later($config['delay_time'], 'app\job\push@addVoteRecord', $record);
                } else {
                    Queue::push('app\job\push@addVoteRecord', $record);
                }

                return json(['code' => 108, 'message' => '点赞成功']);
            } else {
                return json(['code' => 110, 'message' => '点赞失败']);
            }
        }
//        } else {
//            return json(['code' => 110, 'message' => '网络请求失败']);
//        }
    }

    /**
     * 获取红包金额
     * @param $redpacketId
     * @param $status
     * @return array|null|\PDOStatement|string|\think\Model
     */
    private function getRedPaceketInfo($redpacketId, $status)
    {

        $redpacket = Db::name('tp_redpacket')->find($redpacketId);
        Db::name('tp_redpacket')->where('id', $redpacketId)->setField('status', $status);
        return $redpacket;
    }


    /**
     * 更新劲酒优惠券
     * @param $couponId
     * @param $status
     * @return int
     */
    private function updateCouponInfo($couponId, $status)
    {

        $result = Db::name('tp_coupon')->where('code', $couponId)->setField('status', $status);
        return $result;
    }
}
